<template>
  <div class="daily-expense-management">
    <h2 class="title">日常开销管理</h2>
    <div class="toolbar">
      <el-input
          v-model="searchQuery"
          placeholder="搜索开销事项"
          style="width: 200px; margin-right: 10px;"
          @input="fetchExpenses"
      />
      <el-button type="primary" @click="openAddDialog">添加开销</el-button>
    </div>
    <el-dialog :visible.sync="dialogVisible" title="添加/编辑开销" width="40%" @close="handleDialogClose">
      <el-form :model="newExpense" :rules="rules" ref="expenseForm" class="expense-form" label-width="120px">
        <el-form-item label="开销事项" prop="expenseItem">
          <el-input v-model="newExpense.expenseItem"></el-input>
        </el-form-item>
        <el-form-item label="开销类型" class="expense-type-item" prop="expenseType">
          <el-radio-group v-model="newExpense.expenseType">
            <el-radio :label="0">美容美发</el-radio>
            <el-radio :label="1">日常交通</el-radio>
            <el-radio :label="2">物品修理</el-radio>
            <el-radio :label="3">医疗</el-radio>
            <el-radio :label="4">旅游</el-radio>
            <el-radio :label="5">网络话费</el-radio>
            <el-radio :label="6">餐饮娱乐</el-radio>
            <el-radio :label="7">书籍考试</el-radio>
            <el-radio :label="8">水电房租</el-radio>
            <el-radio :label="9">其他</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="开销金额" prop="amount">
          <el-input v-model="newExpense.amount" type="number"></el-input>
        </el-form-item>
        <el-form-item label="金额单位" prop="currencyUnit">
          <el-radio-group v-model="newExpense.currencyUnit">
            <el-radio label="人民币">人民币</el-radio>
            <el-radio label="美元">美元</el-radio>
            <el-radio label="日元">日元</el-radio>
            <el-radio label="韩元">韩元</el-radio>
            <el-radio label="欧元">欧元</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="支出凭证" prop="receipt">
          <el-upload
              class="upload"
              action="http://127.0.0.1:10001/api/upload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :file-list="fileList"
              :headers="headers"
              :on-success="handleSuccess"
              :on-change="handleFileChange"
              :before-upload="beforeUpload"
              :limit="5"
              accept=".jpg,.png"
              :on-exceed="handleExceed"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传.jpg,.png文件，且不超过5个</div>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="validateForm">{{ isEditing ? '更新' : '添加' }}</el-button>
          <el-button @click="resetForm">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <div class="table-container">
      <el-table :data="expenses" style="width: 100%" class="expense-table">
        <el-table-column prop="expenseItem" label="开销事项"></el-table-column>
        <el-table-column prop="expenseType" label="开销类型" :formatter="formatExpenseType"></el-table-column>
        <el-table-column prop="amount" label="开销金额"></el-table-column>
        <el-table-column prop="currencyUnit" label="金额单位"></el-table-column>
        <el-table-column prop="createdAt" label="创建时间" :formatter="formatDate"></el-table-column>
        <el-table-column prop="updatedAt" label="修改时间" :formatter="formatDate"></el-table-column>
        <el-table-column prop="receipt" label="支出凭证">
          <template slot-scope="scope">
            <el-button size="mini" @click="handlePreview({ url: scope.row.receipt })">预览</el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" @click="editExpense(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="confirmDelete(scope.row.id)">删除</el-button>
            <el-button size="mini" @click="showDetails(scope.row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
            background
            layout="prev, pager, next"
            :total="total"
            :page-size="pageSize"
            :current-page.sync="page"
            @current-change="fetchExpenses"
        ></el-pagination>
      </div>
    </div>
    <!-- 图片预览对话框 -->
    <el-dialog v-model="receiptDialogVisible" title="图片预览">
      <img v-if="receiptImageUrl" :src="receiptImageUrl" alt="Preview Image" style="max-width: 100%;">
    </el-dialog>
    <el-dialog :visible.sync="detailsDialogVisible" title="开销详情" width="40%">
      <el-form :model="detailsExpense" label-width="120px" class="expense-form">
        <el-form-item label="开销事项">
          <el-input :value="detailsExpense.expenseItem" disabled></el-input>
        </el-form-item>
        <el-form-item label="开销类型">
          <el-input :value="formatExpenseType(detailsExpense, null, detailsExpense.expenseType)" disabled></el-input>
        </el-form-item>
        <el-form-item label="开销金额">
          <el-input :value="detailsExpense.amount" disabled></el-input>
        </el-form-item>
        <el-form-item label="金额单位">
          <el-input :value="detailsExpense.currencyUnit" disabled></el-input>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-input :value="formatDate(detailsExpense, null, detailsExpense.createdAt)" disabled></el-input>
        </el-form-item>
        <el-form-item label="修改时间">
          <el-input :value="formatDate(detailsExpense, null, detailsExpense.updatedAt)" disabled></el-input>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';
import { Message, MessageBox } from 'element-ui';

export default {
  name: 'DailyExpenseManagement',
  data() {
    return {
      expenses: [],
      searchQuery: '',
      newExpense: {
        id: '',
        expenseItem: '',
        expenseType: '',
        amount: '',
        currencyUnit: '',
        createdAt: '',
        updatedAt: '',
        receipt: ''
      },
      detailsExpense: {
        expenseItem: '',
        expenseType: '',
        amount: '',
        currencyUnit: '',
        createdAt: '',
        updatedAt: '',
        receipt: ''
      },
      headers: {
        token: localStorage.getItem('token'),
      },
      fileList: [], // 已上传的文件列表
      isEditing: false,
      total: 0,
      page: 1,
      pageSize: 10,
      dialogVisible: false,
      detailsDialogVisible: false,
      rules: {
        expenseItem: [{ required: true, message: '请输入开销事项', trigger: 'blur' }],
        expenseType: [{ required: true, message: '请选择开销类型', trigger: 'change' }],
        amount: [{ required: true, message: '请输入开销金额', trigger: 'blur' }],
        currencyUnit: [{ required: true, message: '请选择金额单位', trigger: 'change' }],
        // receipt: [{ required: true, message: '请上传支出凭证', trigger: 'change' }] // 添加新的验证规则
      },
      receiptDialogVisible: false,
      receiptImageUrl: '',
      receiptFile: null // 用于保存原始文件对象
    };
  },
  created() {
    this.fetchExpenses();
  },
  methods: {
    fetchExpenses() {
      axios.get('/daily-expenses', {
        params: {
          page: this.page,
          pageSize: this.pageSize,
          expenseItem: this.searchQuery
        }
      })
          .then(response => {
            this.expenses = response.data.data.rows;
            this.total = response.data.data.records;
          })
          .catch(error => {
            console.error('Error fetching expenses:', error);
          });
    },
    addExpense() {
      axios.post('/daily-expenses', this.newExpense)
          .then(() => {
            this.fetchExpenses();
            this.resetForm();
            Message.success('添加成功');
          })
          .catch(error => {
            console.error('Error adding expense:', error);
          });
    },
    editExpense(expense) {
      this.newExpense = { ...expense };
      this.isEditing = true;
      this.dialogVisible = true;
    },
    updateExpense() {
      axios.put(`/daily-expenses/${this.newExpense.id}`, this.newExpense)
          .then(() => {
            this.fetchExpenses();
            this.resetForm();
            Message.success('更新成功');
          })
          .catch(error => {
            console.error('Error updating expense:', error);
          });
    },
    confirmDelete(id) {
      MessageBox.confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteExpense(id);
      }).catch(() => {
        Message.info('已取消删除');
      });
    },
    deleteExpense(id) {
      axios.delete(`/daily-expenses/${id}`)
          .then(() => {
            this.fetchExpenses();
            Message.success('删除成功');
          })
          .catch(error => {
            console.error('Error deleting expense:', error);
          });
    },
    resetForm() {
      this.newExpense = {
        id: '',
        expenseItem: '',
        expenseType: '',
        amount: '',
        currencyUnit: '',
        createdAt: '',
        updatedAt: '',
        receipt: ''
      };
      this.isEditing = false;
      this.dialogVisible = false;
    },
    handleDialogClose() {
      this.resetForm();
    },
    openAddDialog() {
      this.resetForm();
      this.isEditing = false;
      this.dialogVisible = true;
    },
    validateForm() {
      this.$refs.expenseForm.validate((valid) => {
        if (valid) {
          this.isEditing ? this.updateExpense() : this.addExpense();
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    formatExpenseType(row, column, value) {
      const types = ['美容美发', '日常交通', '物品修理', '医疗', '旅游', '网络话费', '餐饮娱乐', '书籍考试', '水电房租', '其他'];
      return types[value] || value;
    },
    formatDate(row, column, value) {
      if (!value) return '';
      const date = new Date(value);
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`;
    },
    showDetails(expense) {
      this.detailsExpense = { ...expense };
      this.detailsDialogVisible = true;
    },
    handlePreview(file) {
      this.receiptImageUrl = file.url;
      this.receiptDialogVisible = true;
    },
    handleSuccess(response, file, fileList) {
      console.log(file, fileList);
      this.newExpense.receipt = response;
    },
    beforeUpload(file) {
      const isLT2M = file.size / 1024 / 1024 < 2;
      if (!isLT2M) {
        this.$message.error('上传文件大小不能超过 2MB!');
      }
      return isLT2M;
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 5 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    handleRemove(file) {
      this.fileList = this.fileList.filter(item => item.uid !== file.uid);
      this.newExpense.receipt = '';
    },
    handleFileChange(file, fileList) {
      this.fileList = fileList;
    },
  }
};
</script>

<style scoped>
.daily-expense-management {
  height: 100vh;
  overflow: hidden;
  background-image: url('../assets/pdx.png');
  background-size: cover;
  background-position: center;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: center;
  padding: 20px;
  box-sizing: border-box;
}

.title {
  color: black;
  margin-top: 20px;
}

.toolbar {
  width: 100%;
  display: flex;
  justify-content: flex-start;
  margin-bottom: 20px;
}

.expense-form {
  width: 100%;
  margin-bottom: 20px;
}

.el-form-item {
  margin-bottom: 10px;
}

.expense-type-item .el-form-item__content {
  display: flex;
  flex-direction: column;
}

.expense-list {
  width: 100%;
}

/* 新增表格样式 */
.expense-table .el-table__header-wrapper th, .expense-table .el-table__body-wrapper td {
  padding: 5px 10px;
  font-size: 12px;
  line-height: 1.2;
}

/* 表格容器样式 */
.table-container {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  flex-grow: 1;
  overflow: hidden; /* 防止内部滚动 */
}

/* 新增分页组件样式 */
.pagination-container {
  width: 100%;
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
  padding-right: 10px;
}
</style>
